import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, TreeSelect, Select } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import EditTable from './components/EditTable/EditTable';
import { transTitle, handleReturnArray } from '@/utils/utils';
import Bmap from '@/components/Bmap/index.jsx';
import {
  queryRule,
  updateRule,
  addRule,
  removeRule,
  // queryModuleRule,
  queryModelRule,
  editDeviceContent,
  editDeviceArea,
  queryModuleInitRule,
  queryCommunityStreetRule,
} from './service';
import FormItem from 'antd/lib/form/FormItem';

/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    const response = await addRule({ ...fields });
    const { code } = response;
    hide();
    if (code === 0) {
      message.success('添加成功');
    } else {
      message.error('添加失败请重试！');
    }
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在修改');

  try {
    await updateRule(fields);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule({
      key: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [templateModalVisible, handleTemplateModalVisible] = useState(false);
  const [addDeviceModalVisible, handleAddDeviceModalVisible] = useState(false);
  const [editDeviceModalVisible, handleEditDeviceModalVisible] = useState(false);
  const [createAddressModalVisible, handleAddressModalVisible] = useState(false);
  const [createMapModalVisible, handleMapModalVisible] = useState(false);
  const [formValue, setFormValue] = useState(null);
  const [mapValue, setMapValue] = useState({});
  const [pointData, setPointData] = useState({});
  const [modelData, setModelData] = useState([]);
  const [count, setCount] = useState({});
  const [menuValues, setMenuValues] = useState([]);
  const [orgTreeValue, handleOrgTreeValue] = useState();
  const [orgMenuValues, setOrgMenuValues] = useState([]);
  const [moduleMenuValues, setModuleMenuValues] = useState([]);
  const [treeValue, handleTreeValue] = useState();
  const [moduleTreeValue, handleModuleTreeValue] = useState();
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [textId, setTextId] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const handleChoicePlace = (e) => {
    if (e.hasOwnProperty('point')) {
      setPointData(e);
    }
  };
  const handleInitModuleList = async () => {
    try {
      const response = await queryModuleInitRule({ parent: true });
      const { data } = response;
      transTitle(data);
      setModuleMenuValues(data);
      return true;
    } catch (error) {
      return false;
    }
  };
  const handleModuleList = async (terminalId) => {
    try {
      const response = await queryModuleInitRule({ terminalId: terminalId });
      const { data } = response;
      transTitle(data);
      handleModuleTreeValue(data);
      return true;
    } catch (error) {
      return false;
    }
  };
  const handleModelList = async () => {
    try {
      const response = await queryModelRule();
      const {
        data: { list },
      } = response;
      setModelData(list);
      return true;
    } catch (error) {
      return false;
    }
  };

  const handleQueryCommunity = async (payload) => {
    try {
      const response = await queryCommunityStreetRule({ type: 4, areaId: payload });
      const { data } = response;
      transTitle(data);
      setOrgMenuValues(data);
      return true;
    } catch (error) {
      return false;
    }
  };
  const TreeOnChange = (value) => {
    handleTreeValue(value);
    handleQueryCommunity(value.value);
  };

  const orgTreeOnChange = (value) => {
    handleOrgTreeValue(value);
  };

  const moduleTreeOnChange = (value) => {
    handleModuleTreeValue(value);
  };
  const handleBindArea = async (actionRef) => {
    const hide = message.loading('正在设置');
    const payload = {
      id: row.id,
      areaId: treeValue.value,
    };
    try {
      await editDeviceArea(payload);
      hide();
      message.success('设置成功');
      handleAddressModalVisible(false);
      actionRef.current.reload();
      return true;
    } catch (error) {
      hide();
      message.error('设置失败请重试！');
      return false;
    }
  };
  const handleBindModule = async (actionRef) => {
    const hide = message.loading('正在设置');
    const list = [];
    moduleTreeValue.map((item) => {
      list.push({
        terminalId: row.id,
        serviceModuleId: item.value,
        areaId: row.areaId,
      });
    });
    try {
      await editDeviceContent(list);
      hide();
      message.success('设置成功');
      handleModalVisible(false);
      actionRef.current.reload();
      return true;
    } catch (error) {
      hide();
      message.error('设置失败请重试！');
      return false;
    }
  };
  useEffect(() => {
    handleInitModuleList();
    handleModelList();
    return () => {
      setModuleMenuValues(null);
      setMenuValues(null);
      setModelData(null);
    };
  }, []);

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'text',
      hideInSearch: true,
      hideInForm: true,
      width: 300,
    },
    {
      title: '设备名称',
      dataIndex: 'name',
      valueType: 'text',
      width: 160,
    },
    {
      title: '设备型号',
      dataIndex: 'sn',
      valueType: 'text',
      width: 160,
    },
    {
      title: '机型',
      dataIndex: 'modelId',
      valueType: 'text',
      width: 160,
      render: (_, record) => {
        return <span>{record.model ? record.model.name : ''}</span>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false}>
            <Select
              showSearch
              placeholder="选择机型"
              optionFilterProp="children"
              filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {modelData.map((item_in) => {
                return (
                  <Option key={item_in.id} value={item_in.id}>
                    {item_in.name}
                  </Option>
                );
              })}
            </Select>
          </FormItem>
        );
      },
    },
    {
      title: '所属区域',
      dataIndex: 'areaId',
      valueType: 'text',
      width: 160,
      // hideInSearch: true,
      render: (_, record) => {
        return <span>{record.area ? record.area.name : ''}</span>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false}>
            <TreeSelect
              showSearch
              // style={{ width: '400px' }}
              labelInValue
              value={treeValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择父级"
              allowClear
              treeDataSimpleMode
              treeData={menuValues}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onChange={TreeOnChange}
            />
          </FormItem>
        );
      },
    },
    {
      title: '所属机构',
      dataIndex: 'orgId',
      valueType: 'text',
      width: 800,
      // hideInSearch: true,
      render: (_, record) => {
        return <span>{record.org ? record.org.name : '-'}</span>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false}>
            <TreeSelect
              showSearch
              // style={{ width: '400px' }}
              labelInValue
              value={orgTreeValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择父级"
              allowClear
              treeDataSimpleMode
              treeData={orgMenuValues}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onChange={orgTreeOnChange}
            />
          </FormItem>
        );
      },
    },
    {
      title: '所属IP',
      dataIndex: 'ip',
      valueType: 'text',
      hideInSearch: true,
      hideInForm: true,
      width: 160,
    },
    {
      title: '是否在线',
      dataIndex: 'isOnline',
      width: 120,
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Default',
          value: 0,
        },
        1: {
          text: '运行中',
          status: 'Processing',
          value: 1,
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} name="isOnline">
            <Select placeholder="请选择">
              {handleReturnArray(item.valueEnum, 3).map((item_in, index) => {
                if (item_in) {
                  return (
                    <Option key={index} value={item_in.value}>
                      {item_in.text}
                    </Option>
                  );
                }
              })}
            </Select>
          </FormItem>
        );
      },
    },
    {
      title: '上一次连接时间',
      dataIndex: 'lastTime',
      valueType: 'date',
      hideInSearch: true,
      hideInForm: true,
      width: 160,
    },
    {
      title: '设备位置',
      dataIndex: 'position',
      valueType: 'text',
      width: 200,
      hideInSearch: true,
      hideInForm: true,
      render: (_, record) => {
        return (
          <div
            style={{ cursor: 'pointer', color: '#1890ff' }}
            onClick={() => {
              setMapValue({
                address: record.addressName ? record.addressName : '',
                point: {
                  lat: record.mapLatitude,
                  lng: record.mapLongitude,
                },
                device: true,
              });
              handleMapModalVisible(true);
            }}
          >
            查看
          </div>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            <Bmap
              size={{ height: 500 }}
              value={pointData}
              onChange={(e) => {
                handleChoicePlace(e);
              }}
            />
          </>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 340,
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              setFormValue(record);
              handleTreeValue({
                value: record.area.id,
                label: record.area.name,
              });
              handleOrgTreeValue({
                value: record.org.id,
                label: record.org.name,
              });
              // setSelectedRowKeysArray([record.screenId]);
              // setTextId(record.screenId);
              handleQueryCommunity(record.areaId);
              handleEditDeviceModalVisible(true);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              setRow(record);
              handleTreeValue({
                label: record.areaName,
                value: record.areaId,
              });
              // setSelectedRowKeysArray([record.screenId]);
              // setTextId(record.screenId);
              handleTemplateModalVisible(true);
            }}
          >
            系统配置
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              setRow(record);
              handleModuleList(record.id);
              // setSelectedRowKeysArray([record.screenId]);
              // setTextId(record.screenId);
              handleModalVisible(true);
            }}
          >
            业务配置
          </a>
          {/* <Divider type="vertical" />
          <a
            onClick={() => {
              setFormValue(record);
              handleTreeValue({
                value: record.areaId,
                label: record.areaName,
              });
              // setSelectedRowKeysArray([record.screenId]);
              // setTextId(record.screenId);
              handleEditDeviceModalVisible(true);
            }}
          >
            选择区域
          </a> */}
        </>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        bordered
        scroll={{ x: '130vw' }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleAddDeviceModalVisible(true);
              setOrgMenuValues([]);
            }}
          >
            <PlusOutlined /> 添加设备
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          const { list, total } = payload;
          setCount(total);
          return list;
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        beforeSearchSubmit={(payload) => {
          payload.areaId = payload.areaName;
          delete payload.areaName;
          return payload;
        }}
        columns={columns}
        rowSelection={false}
      />
      <CreateForm
        width={600}
        onCancel={() => handleModalVisible(false)}
        title="业务配置"
        modalVisible={createModalVisible}
      >
        <TreeSelect
          showSearch
          style={{ width: '400px', marginRight: '5px' }}
          labelInValue
          value={moduleTreeValue}
          dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
          placeholder="请选择业务模块"
          allowClear
          treeDataSimpleMode
          treeCheckable
          treeData={moduleMenuValues}
          treeNodeFilterProp="title"
          treeNodeLabelProp="title"
          onChange={moduleTreeOnChange}
        />
        <Button
          onClick={() => {
            handleBindModule(actionRef);
          }}
          type="primary"
        >
          保存
        </Button>
      </CreateForm>
      <CreateForm
        onCancel={() => handleMapModalVisible(false)}
        modalVisible={createMapModalVisible}
        title="设备位置"
      >
        <Bmap size={{ width: 400, height: 350, marginLeft: '8%' }} value={mapValue} />
      </CreateForm>
      <CreateForm
        onCancel={() => handleAddressModalVisible(false)}
        modalVisible={createAddressModalVisible}
        title="修改位置"
      >
        <TreeSelect
          showSearch
          style={{ width: '400px', marginRight: '5px' }}
          labelInValue
          value={treeValue}
          dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
          placeholder="请选择所在地"
          allowClear
          treeDataSimpleMode
          treeData={menuValues}
          treeNodeFilterProp="title"
          treeNodeLabelProp="title"
          onChange={TreeOnChange}
        />
        <Button
          onClick={() => {
            handleBindArea(actionRef);
          }}
          type="primary"
        >
          保存
        </Button>
      </CreateForm>

      <CreateForm
        onCancel={() => handleAddDeviceModalVisible(false)}
        modalVisible={addDeviceModalVisible}
        title="添加设备"
      >
        <ProTable
          onSubmit={async (value) => {
            value.areaId = value.areaId.value;
            value.areaName = value.areaId.label;
            value.orgId = value.orgId.value;
            value.orgName = value.orgId.label;
            const success = await handleAdd(value);

            if (success) {
              handleAddDeviceModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>

      <CreateForm
        onCancel={() => handleEditDeviceModalVisible(false)}
        modalVisible={editDeviceModalVisible}
        title="修改设备"
      >
        <ProTable
          onSubmit={async (value) => {
            value.version = formValue.version + 1;
            value.id = formValue.id;
            value.areaId = treeValue.value;
            value.areaName = treeValue.label;
            value.orgName = orgTreeValue.label;
            value.orgId = orgTreeValue.value;
            const success = await handleUpdate(value);

            if (success) {
              handleEditDeviceModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{ initialValues: formValue }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>

      <CreateForm
        onCancel={() => handleTemplateModalVisible(false)}
        modalVisible={templateModalVisible}
        title="系统配置"
        width={1400}
      >
        <EditTable deviceInfo={row} />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
